#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
使用tepian.png素材创建微信公众号草稿
直接使用已知的素材ID创建草稿
"""

import requests
import json
from config import WECHAT_CONFIG
from wechat_token import WeChatTokenManager

def create_draft_with_tepian_media_id():
    """使用tepian.png的Media ID创建草稿"""
    
    print("=== 使用tepian.png素材创建草稿 ===")
    
    # 使用您上传成功的素材ID
    TEPIAN_MEDIA_ID = "loZScAtjldzC9kSbORaEJkBk_yVKFTM0m7DHhxNPwA1vSPncW7aIPsAJb-NgG6wr"
    
    print(f"📋 使用素材ID: {TEPIAN_MEDIA_ID}")
    
    # 创建token管理器
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    
    try:
        # 获取access token
        access_token = token_manager.get_access_token()
        print(f"✅ 获取Access Token成功")
        
        # 构建草稿数据
        draft_data = {
            "articles": [
                {
                    "article_type": "news",
                    "title": "欢迎关注我们的公众号！",
                    "author": "公众号团队",
                    "digest": "感谢您的关注，我们将为您提供优质内容",
                    "content": """
                    <section style="margin: 0px; padding: 0px; color: rgb(51, 51, 51); font-family: -apple-system-font, BlinkMacSystemFont, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 17px; letter-spacing: 0.544px; text-align: justify; line-height: 1.75em;">
                        <p style="margin-top: 0px; margin-bottom: 0px; padding: 0px; clear: both; line-height: 1.75em;">
                            <span style="font-size: 16px;">感谢您关注我们的微信公众号！</span>
                        </p>
                    </section>
                    <section style="margin: 10px 0px 0px; padding: 0px; color: rgb(51, 51, 51); font-family: -apple-system-font, BlinkMacSystemFont, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 17px; letter-spacing: 0.544px; text-align: justify; line-height: 1.75em;">
                        <p style="margin-top: 0px; margin-bottom: 0px; padding: 0px; clear: both; line-height: 1.75em;">
                            <span style="font-size: 16px;">我们将为您提供：</span>
                        </p>
                    </section>
                    <section style="margin: 10px 0px 0px; padding: 0px; color: rgb(51, 51, 51); font-family: -apple-system-font, BlinkMacSystemFont, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 17px; letter-spacing: 0.544px; text-align: justify; line-height: 1.75em;">
                        <p style="margin-top: 0px; margin-bottom: 0px; padding: 0px; clear: both; line-height: 1.75em;">
                            <span style="font-size: 16px;">• 最新的行业资讯</span>
                        </p>
                        <p style="margin-top: 0px; margin-bottom: 0px; padding: 0px; clear: both; line-height: 1.75em;">
                            <span style="font-size: 16px;">• 优质的技术内容</span>
                        </p>
                        <p style="margin-top: 0px; margin-bottom: 0px; padding: 0px; clear: both; line-height: 1.75em;">
                            <span style="font-size: 16px;">• 实用的工具分享</span>
                        </p>
                    </section>
                    <section style="margin: 15px 0px 0px; padding: 0px; color: rgb(51, 51, 51); font-family: -apple-system-font, BlinkMacSystemFont, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 17px; letter-spacing: 0.544px; text-align: justify; line-height: 1.75em;">
                        <p style="margin-top: 0px; margin-bottom: 0px; padding: 0px; clear: both; line-height: 1.75em;">
                            <span style="font-size: 16px; color: rgb(136, 136, 136);">如果您有任何问题或建议，欢迎随时与我们联系。</span>
                        </p>
                    </section>
                    <section style="margin: 20px 0px 0px; padding: 15px; background-color: rgb(248, 248, 248); border-radius: 8px; color: rgb(51, 51, 51); font-family: -apple-system-font, BlinkMacSystemFont, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif; font-size: 17px; letter-spacing: 0.544px; text-align: center; line-height: 1.75em;">
                        <p style="margin-top: 0px; margin-bottom: 0px; padding: 0px; clear: both; line-height: 1.75em;">
                            <strong style="color: rgb(96, 127, 255);"><span style="font-size: 18px;">让我们一起成长，一起进步！</span></strong>
                        </p>
                    </section>
                    """,
                    "content_source_url": "",
                    "thumb_media_id": TEPIAN_MEDIA_ID,
                    "need_open_comment": 1,
                    "only_fans_can_comment": 0
                }
            ]
        }
        
        # 发送请求创建草稿
        url = "https://api.weixin.qq.com/cgi-bin/draft/add"
        params = {'access_token': access_token}
        
        print("🚀 正在创建草稿...")
        
        response = requests.post(url, params=params, json=draft_data, timeout=30)
        response.raise_for_status()
        
        result = response.json()
        
        if 'errcode' in result and result['errcode'] != 0:
            print(f"❌ 创建草稿失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            return None
        
        print(f"✅ 草稿创建成功!")
        print(f"📋 草稿Media ID: {result.get('media_id')}")
        
        # 保存结果
        with open('tepian_draft_result.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)
        print(f"💾 草稿结果已保存到: tepian_draft_result.json")
        
        return result
        
    except Exception as e:
        print(f"❌ 创建草稿失败: {e}")
        return None

def get_draft_list():
    """获取草稿列表"""
    print("\n=== 获取草稿列表 ===")
    
    token_manager = WeChatTokenManager(
        WECHAT_CONFIG['APP_ID'], 
        WECHAT_CONFIG['APP_SECRET']
    )
    
    try:
        access_token = token_manager.get_access_token()
        
        url = "https://api.weixin.qq.com/cgi-bin/draft/batchget"
        params = {'access_token': access_token}
        
        data = {
            'offset': 0,
            'count': 10,
            'no_content': 1  # 不返回content字段，节省流量
        }
        
        response = requests.post(url, params=params, json=data, timeout=30)
        response.raise_for_status()
        
        result = response.json()
        
        if 'errcode' in result and result['errcode'] != 0:
            print(f"❌ 获取草稿列表失败: {result['errcode']} - {result.get('errmsg', '未知错误')}")
            return
        
        total_count = result.get('total_count', 0)
        items = result.get('item', [])
        
        print(f"📊 草稿总数: {total_count}")
        print(f"📝 当前显示: {len(items)} 个草稿")
        
        for i, item in enumerate(items):
            print(f"\n草稿 {i+1}:")
            print(f"  📋 Media ID: {item.get('media_id')}")
            print(f"  🕒 更新时间: {item.get('update_time')}")
            
            if item.get('content') and item['content'].get('news_item'):
                news_item = item['content']['news_item'][0]
                print(f"  📰 标题: {news_item.get('title', '无标题')}")
                print(f"  ✍️  作者: {news_item.get('author', '无作者')}")
                print(f"  📄 摘要: {news_item.get('digest', '无摘要')[:50]}...")
        
    except Exception as e:
        print(f"❌ 获取草稿列表失败: {e}")

def main():
    """主函数"""
    print("=== 微信公众号草稿创建工具 ===")
    
    # 检查配置
    if WECHAT_CONFIG['APP_ID'] == 'your_app_id_here':
        print("❌ 请先在config.py中配置您的APP_ID和APP_SECRET")
        return
    
    # 创建草稿
    result = create_draft_with_tepian_media_id()
    
    if result:
        # 获取草稿列表
        get_draft_list()
        
        print("\n✅ 所有操作完成!")
        print("\n💡 您现在可以:")
        print("1. 登录微信公众平台查看草稿")
        print("2. 在草稿箱中编辑和发布内容")
        print("3. 使用草稿Media ID进行其他操作")

if __name__ == '__main__':
    main()
